//
//  MKDownloadListViewController.m
//  ManKeCartoon
//
//  Created by 邹功梁 on 15/10/27.
//  Copyright © 2015年 ManKe. All rights reserved.
//

#import "MKDownloadListViewController.h"
#import "MKDownloadListCollectionViewCell.h"
#import "MKBottomDownloadView.h"
#import "CoreDataManager.h"
#import "DownloadData.h"
@interface MKDownloadListViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) MKBottomDownloadView *bottomView;
@property (nonatomic, assign) NSInteger seqNumber;
@property (nonatomic, retain) MKComicModel *comicModel;

@property (nonatomic, strong) CoreDataManager *coreDataManager;

@property (nonatomic, retain) NSMutableDictionary *comicDic;

@property (nonatomic, retain) NSMutableArray *comicDataArray;

@end

@implementation MKDownloadListViewController
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        _chapterModelArray = [[NSMutableArray alloc] init];
        _downloadModelArray = [[NSMutableArray alloc] init];
        _searchResultArray = [[NSMutableArray alloc] init];
        _downloadModelArray = [[NSMutableArray alloc] init];
        _comicDic = [[NSMutableDictionary alloc] init];
        _comicDataArray = [[NSMutableArray alloc] init];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _seqNumber = 0;
    
    self.coreDataManager = [CoreDataManager shareHandle];
    [self searchDownloadData];
    
    [self customNavBar];
    [self setUpBottomView];
    
    [self getData];
    
}
#pragma mark - 查找下载数组
- (void)searchDownloadData
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"comic_id"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"[Error] %@", error);
    }
    
    self.searchResultArray = [fetchedObjects mutableCopy];
    
    for (DownloadData *down in fetchedObjects) {
        //        // Data 转 Array
        _downloadDataArray = [NSKeyedUnarchiver unarchiveObjectWithData:down.downloadData];
        [_comicDic setValue:_downloadDataArray forKey:down.comic_id];
    }
}
#pragma mark - Data数据处理
- (void)getData
{
//    NSLog(@"!!!!!!!%@", [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/ComicDetailV2/comic_id/%@/", _comic_id]);
    [AFNETWORK getDataWithNoCacheString:[NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/ComicDetailV2/comic_id/%@/", _comic_id] block:^(id block) {
        
        _comicModel = [[MKComicModel alloc] initWithDictionary:[[block objectForKey:@"data"] objectForKey:@"comic"]];
        
        for (NSDictionary *dic in [[block objectForKey:@"data"] objectForKey:@"chapters"]) {
            MKChaptersModel *chaptersModel = [[MKChaptersModel alloc] initWithDictionary:dic];
            
            [_chapterModelArray addObject:chaptersModel];
        }
        
        [self setUpCollectionView];
        CGFloat width = [StringWithWidth WidthWithText:_comicModel.title height:30 * HEIGHT font:[UIFont systemFontOfSize:18.]];
        [_nameLabel setFrame:CGRectMake(SCREEN_WIDTH / 2 - width * WIDTH / 2, 23, width, 30 * HEIGHT)];
        [_nameLabel setText:_comicModel.title];
    }];
}
#pragma mark - SetUpBottomView
- (void)setUpBottomView
{
    _bottomView = [[MKBottomDownloadView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 44 * HEIGHT, SCREEN_WIDTH, 44 * HEIGHT)];
    _bottomView.button.selected = YES;
    [_bottomView.button addTarget:self action:@selector(downloadClick:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView.allButton addTarget:self action:@selector(allChoseClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomView];
}
#pragma mark - 下载按钮点击方法
- (void)downloadClick:(UIButton *)sender
{
    if (sender.selected == NO) {
        NSInteger count = 0;
        for (DownloadData *downData in _searchResultArray) {
            
            if ([downData.comic_id isEqualToString:_comic_id]) {
                [_downloadModelArray addObjectsFromArray:_downloadDataArray];
                downData.downloadData = [NSKeyedArchiver archivedDataWithRootObject:_downloadModelArray];
                [self.coreDataManager saveContext];
            }
            else
            {
                count++;
            }
        }
        if (count == _searchResultArray.count) {
            DownloadData *down = [NSEntityDescription insertNewObjectForEntityForName:@"DownloadData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
            
            down.comic_id = _comic_id;
            down.cover_url = _comicModel.cover_url;
            down.title = _comicModel.title;
            down.downloadData = [NSKeyedArchiver archivedDataWithRootObject:_downloadModelArray];
            [self.coreDataManager saveContext];
            
        }
        
        
        
        
        MKBookshelfViewController *book = [[MKBookshelfViewController alloc] init];
        book.comicModel = _comicModel;
        book.chapterModelArray = _downloadModelArray;
        [self.navigationController pushViewController:book animated:YES];
    }
}
#pragma mark - 全选点击方法
- (void)allChoseClick:(UIButton *)sender
{
    if (sender.selected == NO) {
        for (int i = 0; i < _chapterModelArray.count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            MKDownloadListCollectionViewCell *cell = (MKDownloadListCollectionViewCell *)[_downlistCollectionView cellForItemAtIndexPath:indexPath];
            if (!cell.button.hidden) {
                cell.seq_noLabel.textColor = [UIColor whiteColor];
                cell.backgroundColor = [UIColor orangeColor];
                cell.button.selected = YES;
                _downloadModelArray = [NSMutableArray arrayWithArray:_chapterModelArray];
                _bottomView.button.selected = NO;
            }
        }
    }
    else
    {
        for (int i = 0; i < _chapterModelArray.count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            MKDownloadListCollectionViewCell *cell = (MKDownloadListCollectionViewCell *)[_downlistCollectionView cellForItemAtIndexPath:indexPath];
            if (!cell.button.hidden) {
                cell.seq_noLabel.textColor = [UIColor blackColor];
                cell.backgroundColor = [UIColor whiteColor];
                cell.button.selected = NO;
                [_downloadModelArray removeAllObjects];
                _bottomView.button.selected = YES;
            }

        }
    }
    sender.selected = !sender.selected;
}
#pragma mark - CustomNavBar
- (void)customNavBar
{
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setFrame:CGRectMake(10, 23, 30, 30)];
    [_backButton setImage:[UIImage imageNamed:@"iconfont-arrowleft.png"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView addSubview:_backButton];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _nameLabel.font = [UIFont systemFontOfSize:18.];
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.numberOfLines = 0;
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    [self.navBarView addSubview:_nameLabel];
}
#pragma mark - 返回按钮点击方法
- (void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - SetUpCollectionView
- (void)setUpCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(80 * WIDTH, 40 * HEIGHT);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 20;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    _downlistCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 44 * HEIGHT) collectionViewLayout:flowLayout];
    _downlistCollectionView.delegate = self;
    _downlistCollectionView.dataSource = self;
    [_downlistCollectionView setBackgroundColor:[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1]];
    
    [self.view addSubview:_downlistCollectionView];
    
    [_downlistCollectionView registerClass:[MKDownloadListCollectionViewCell class] forCellWithReuseIdentifier:@"reuseIdentifier"];
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _chapterModelArray.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MKDownloadListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    MKChaptersModel *model = [_chapterModelArray objectAtIndex:indexPath.row];
    [cell setChaptersModel:model];
    cell.backgroundColor = [UIColor whiteColor];
    cell.seq_noLabel.textColor = [UIColor blackColor];
    cell.layer.masksToBounds = YES;
    cell.layer.borderWidth = 1.;
    cell.layer.borderColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1].CGColor;
    [cell.button addTarget:self action:@selector(cellButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.button.selected = NO;
    for (MKChaptersModel *chapterModel in _downloadModelArray) {
        if ([chapterModel.seq_no isEqualToString:model.seq_no]) {
            cell.seq_noLabel.textColor = [UIColor whiteColor];
            cell.backgroundColor = [UIColor orangeColor];
        }
    }
    _comicDataArray = [_comicDic objectForKey:_comicModel.comic_id];
    for (MKChaptersModel *chapterModel in _comicDataArray) {
        if ([chapterModel.seq_no isEqualToString:model.seq_no]) {
            cell.seq_noLabel.textColor = [UIColor grayColor];
            cell.backgroundColor = [UIColor lightGrayColor];
            cell.button.hidden = YES;
        }
    }
    return cell;
}
#pragma mark - Cell Button点击方法
- (void)cellButtonClick:(UIButton *)sender
{
    MKDownloadListCollectionViewCell *cell = (MKDownloadListCollectionViewCell *)sender.superview.superview;
    NSIndexPath *indexPath = [_downlistCollectionView indexPathForCell:cell];
    MKChaptersModel *chaptersModel = [_chapterModelArray objectAtIndex:indexPath.row];
    if (sender.selected == NO) {
        cell.seq_noLabel.textColor = [UIColor whiteColor];
        cell.backgroundColor = [UIColor orangeColor];
        [_downloadModelArray addObject:chaptersModel];
        if (_downloadModelArray.count == _chapterModelArray.count - _downloadDataArray.count) {
            _bottomView.allButton.selected = YES;
        }
        _bottomView.button.selected = NO;
    }
    else
    {
        cell.seq_noLabel.textColor = [UIColor blackColor];
        cell.backgroundColor = [UIColor whiteColor];
        [_downloadModelArray removeObject:chaptersModel];
        if (_downloadModelArray.count < _chapterModelArray.count - _downloadDataArray.count) {
            _bottomView.allButton.selected = NO;
        }
        if (_downloadModelArray.count == 0) {
            _bottomView.button.selected = YES;
        }
    }
    sender.selected = !sender.selected;
}
//- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    MKDownloadListCollectionViewCell *cell = (MKDownloadListCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
//    cell.seq_noLabel.textColor = [UIColor whiteColor];
//    cell.backgroundColor = [UIColor orangeColor];
//    
//    MKChaptersModel *model = [_chapterModelArray objectAtIndex:indexPath.row];
//    if (cell.button.selected == NO) {
//        _seqNumber++;
//        _bottomView.button.selected = NO;
//    }
//}
//- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    MKDownloadListCollectionViewCell *cell = (MKDownloadListCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
////    cell.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.94 alpha:1];
//    cell.seq_noLabel.textColor = [UIColor blackColor];
//    cell.backgroundColor = [UIColor whiteColor];
//    
//    if (cell.button.selected == YES) {
//        _seqNumber--;
//    }
//    if (_seqNumber == 0) {
//        _bottomView.button.selected = YES;
//    }
//    
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
